Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,40 +4,62 @@ import gradio as gr
|
|
| 4 |
import numpy as np
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
# Ensure log file directory is writable
|
| 9 |
-
LOG_FILE = os.path.join(os.path.dirname(__file__), "phishing_urls.log")
|
| 10 |
|
| 11 |
-
|
| 12 |
-
phishing_logger = logging.getLogger('phishing')
|
| 13 |
-
phishing_logger.setLevel(logging.INFO)
|
| 14 |
-
phishing_handler = logging.FileHandler(LOG_FILE, mode='a', force=True) # Force flush writes
|
| 15 |
-
phishing_handler.setFormatter(logging.Formatter('%(asctime)s | Confidence: %(confidence)s% | %(message)s'))
|
| 16 |
-
phishing_logger.addHandler(phishing_handler)
|
| 17 |
-
phishing_logger.info("Logger initialized") # Debug log to confirm setup
|
| 18 |
|
| 19 |
-
# Set up a separate logger for system logs
|
| 20 |
-
system_logger = logging.getLogger('system')
|
| 21 |
-
system_logger.setLevel(logging.INFO)
|
| 22 |
-
system_handler = logging.StreamHandler() # Console output
|
| 23 |
-
system_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
|
| 24 |
-
system_logger.addHandler(system_handler)
|
| 25 |
-
|
| 26 |
-
# Prevent root logger interference
|
| 27 |
-
logging.getLogger('').handlers = []
|
| 28 |
-
|
| 29 |
-
# Initialize Hugging Face model for phishing detection
|
| 30 |
model = pipeline('text-classification', model="Ajay1311/phish")
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
def create_speedometer_chart(confidence, is_phishing):
|
| 43 |
"""Generate speedometer chart showing confidence of phishing detection."""
|
|
@@ -65,7 +87,7 @@ def create_speedometer_chart(confidence, is_phishing):
|
|
| 65 |
return fig
|
| 66 |
|
| 67 |
def analyze_phishing(text):
|
| 68 |
-
"""Function to analyze if text contains phishing content and
|
| 69 |
if not text.strip():
|
| 70 |
return "No input provided.", None, "Please enter valid email or URL content for analysis."
|
| 71 |
|
|
@@ -89,9 +111,12 @@ def analyze_phishing(text):
|
|
| 89 |
**Recommendation:** Do not interact with the content until verified by your IT or security team.
|
| 90 |
"""
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
else:
|
| 97 |
analysis = f"""
|
|
@@ -117,20 +142,6 @@ def open_awareness_page():
|
|
| 117 |
<p>Opening CyberSwaRaksha awareness page...</p>
|
| 118 |
"""
|
| 119 |
|
| 120 |
-
def download_log_file():
|
| 121 |
-
"""Return the path to the log file for download."""
|
| 122 |
-
try:
|
| 123 |
-
if os.path.exists(LOG_FILE):
|
| 124 |
-
# Ensure file is readable
|
| 125 |
-
os.chmod(LOG_FILE, 0o644) # Set read/write for owner, read for others
|
| 126 |
-
if os.path.getsize(LOG_FILE) > 0:
|
| 127 |
-
return LOG_FILE
|
| 128 |
-
return None, "Log file exists but is empty. Try analyzing more inputs."
|
| 129 |
-
return None, "No phishing detections logged yet."
|
| 130 |
-
except Exception as e:
|
| 131 |
-
system_logger.error(f"Error accessing log file {LOG_FILE}: {e}")
|
| 132 |
-
return None, f"Error accessing log file: {e}"
|
| 133 |
-
|
| 134 |
theme = gr.themes.Soft(primary_hue="blue", secondary_hue="gray").set(
|
| 135 |
button_primary_background_fill="*primary_600",
|
| 136 |
button_primary_text_color="white",
|
|
@@ -159,14 +170,12 @@ with gr.Blocks(theme=theme, css="""
|
|
| 159 |
with gr.Row():
|
| 160 |
analyze_btn = gr.Button("Analyze", variant="primary")
|
| 161 |
awareness_btn = gr.Button("Cyber Safety Tips", variant="secondary")
|
| 162 |
-
download_btn = gr.Button("Download Log", variant="secondary")
|
| 163 |
clear_btn = gr.Button("Clear")
|
| 164 |
|
| 165 |
with gr.Group():
|
| 166 |
result_text = gr.Textbox(label="Detection Summary", elem_classes="result-box")
|
| 167 |
result_plot = gr.Plot(label="Confidence Meter")
|
| 168 |
analysis_md = gr.Markdown(label="Detailed Analysis")
|
| 169 |
-
log_file = gr.File(label="Phishing Log File")
|
| 170 |
|
| 171 |
analyze_btn.click(
|
| 172 |
analyze_phishing,
|
|
@@ -180,16 +189,10 @@ with gr.Blocks(theme=theme, css="""
|
|
| 180 |
outputs=gr.HTML(label="Awareness Page")
|
| 181 |
)
|
| 182 |
|
| 183 |
-
download_btn.click(
|
| 184 |
-
download_log_file,
|
| 185 |
-
inputs=None,
|
| 186 |
-
outputs=[log_file, analysis_md]
|
| 187 |
-
)
|
| 188 |
-
|
| 189 |
clear_btn.click(
|
| 190 |
-
lambda: ("", None, ""
|
| 191 |
inputs=None,
|
| 192 |
-
outputs=[input_text, result_plot, analysis_md
|
| 193 |
)
|
| 194 |
|
| 195 |
gr.HTML("""<div class="footer">Cyber Swa Raksha</div>""")
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
from transformers import pipeline
|
| 7 |
+
import smtplib
|
| 8 |
+
from email.mime.text import MIMEText
|
| 9 |
+
from email.mime.multipart import MIMEMultipart
|
| 10 |
+
import time
|
| 11 |
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
logging.basicConfig(filename='phishing_urls.log', level=logging.INFO, format='%(asctime)s - %(message)s')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
model = pipeline('text-classification', model="Ajay1311/phish")
|
| 16 |
|
| 17 |
+
SMTP_SERVER = "smtp.gmail.com"
|
| 18 |
+
SMTP_PORT = 465 # Try 465 for SSL if 587 fails
|
| 19 |
+
SENDER_EMAIL = "pukumar2003@gmail.com"
|
| 20 |
+
SENDER_PASSWORD = "qwaw bfdb xdlt qyup"
|
| 21 |
+
RECIPIENT_EMAIL = "pukumar2003@gmail.com"
|
| 22 |
+
IS_HUGGINGFACE_SPACES = "false".lower() == "true"
|
| 23 |
+
|
| 24 |
+
def send_email_via_gmail(subject, body, use_ssl=False):
|
| 25 |
+
"""Function to send email via Gmail SMTP server with retries."""
|
| 26 |
+
if IS_HUGGINGFACE_SPACES:
|
| 27 |
+
logging.warning("Email sending disabled in Hugging Face Spaces due to SMTP restrictions.")
|
| 28 |
+
return "Email sending disabled in Hugging Face Spaces due to network restrictions."
|
| 29 |
+
|
| 30 |
+
message = MIMEMultipart()
|
| 31 |
+
message["From"] = SENDER_EMAIL
|
| 32 |
+
message["To"] = RECIPIENT_EMAIL
|
| 33 |
+
message["Subject"] = subject
|
| 34 |
+
message.attach(MIMEText(body, "plain"))
|
| 35 |
+
|
| 36 |
+
max_retries = 3
|
| 37 |
+
retry_delay = 5 # seconds
|
| 38 |
+
timeout = 10 # seconds
|
| 39 |
+
port = 465 if use_ssl else SMTP_PORT
|
| 40 |
+
for attempt in range(max_retries):
|
| 41 |
+
try:
|
| 42 |
+
if use_ssl:
|
| 43 |
+
with smtplib.SMTP_SSL(SMTP_SERVER, port, timeout=timeout) as server:
|
| 44 |
+
server.login(SENDER_EMAIL, SENDER_PASSWORD)
|
| 45 |
+
server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
|
| 46 |
+
else:
|
| 47 |
+
with smtplib.SMTP(SMTP_SERVER, port, timeout=timeout) as server:
|
| 48 |
+
server.starttls()
|
| 49 |
+
server.login(SENDER_EMAIL, SENDER_PASSWORD)
|
| 50 |
+
server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
|
| 51 |
+
logging.info(f"Email sent successfully via port {port}")
|
| 52 |
+
return "Phishing report email sent successfully!"
|
| 53 |
+
except (smtplib.SMTPException, OSError) as e:
|
| 54 |
+
logging.error(f"Failed to send email via port {port} (attempt {attempt + 1}/{max_retries}): {e}")
|
| 55 |
+
if attempt < max_retries - 1:
|
| 56 |
+
time.sleep(retry_delay)
|
| 57 |
+
continue
|
| 58 |
+
return f"Failed to send email: {e}"
|
| 59 |
+
|
| 60 |
+
def log_phishing(url_or_text):
|
| 61 |
+
"""Log phishing URLs or content into a log file."""
|
| 62 |
+
logging.info(f"Phishing detected: {url_or_text}")
|
| 63 |
|
| 64 |
def create_speedometer_chart(confidence, is_phishing):
|
| 65 |
"""Generate speedometer chart showing confidence of phishing detection."""
|
|
|
|
| 87 |
return fig
|
| 88 |
|
| 89 |
def analyze_phishing(text):
|
| 90 |
+
"""Function to analyze if text contains phishing content and perform actions accordingly."""
|
| 91 |
if not text.strip():
|
| 92 |
return "No input provided.", None, "Please enter valid email or URL content for analysis."
|
| 93 |
|
|
|
|
| 111 |
**Recommendation:** Do not interact with the content until verified by your IT or security team.
|
| 112 |
"""
|
| 113 |
|
| 114 |
+
# Try sending email with port 587, fallback to 465
|
| 115 |
+
email_result = send_email_via_gmail("Phishing Detected", f"Phishing detected with confidence {score*100:.1f}%: {text}")
|
| 116 |
+
if "Failed to send email" in email_result:
|
| 117 |
+
email_result = send_email_via_gmail("Phishing Detected", f"Phishing detected with confidence {score*100:.1f}%: {text}", use_ssl=True)
|
| 118 |
+
log_phishing(text)
|
| 119 |
+
analysis += f"\n**Email Notification:** {email_result}"
|
| 120 |
|
| 121 |
else:
|
| 122 |
analysis = f"""
|
|
|
|
| 142 |
<p>Opening CyberSwaRaksha awareness page...</p>
|
| 143 |
"""
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
theme = gr.themes.Soft(primary_hue="blue", secondary_hue="gray").set(
|
| 146 |
button_primary_background_fill="*primary_600",
|
| 147 |
button_primary_text_color="white",
|
|
|
|
| 170 |
with gr.Row():
|
| 171 |
analyze_btn = gr.Button("Analyze", variant="primary")
|
| 172 |
awareness_btn = gr.Button("Cyber Safety Tips", variant="secondary")
|
|
|
|
| 173 |
clear_btn = gr.Button("Clear")
|
| 174 |
|
| 175 |
with gr.Group():
|
| 176 |
result_text = gr.Textbox(label="Detection Summary", elem_classes="result-box")
|
| 177 |
result_plot = gr.Plot(label="Confidence Meter")
|
| 178 |
analysis_md = gr.Markdown(label="Detailed Analysis")
|
|
|
|
| 179 |
|
| 180 |
analyze_btn.click(
|
| 181 |
analyze_phishing,
|
|
|
|
| 189 |
outputs=gr.HTML(label="Awareness Page")
|
| 190 |
)
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
clear_btn.click(
|
| 193 |
+
lambda: ("", None, ""),
|
| 194 |
inputs=None,
|
| 195 |
+
outputs=[input_text, result_plot, analysis_md]
|
| 196 |
)
|
| 197 |
|
| 198 |
gr.HTML("""<div class="footer">Cyber Swa Raksha</div>""")
|