🛡️ ZeroPhish Gate
AI-Powered Phishing & Threat Detection
Analyze messages, emails, and documents for potential security threats
import os
import re
import gradio as gr
from datetime import datetime
import tempfile
import io
import base64
# Check for required dependencies
try:
import fitz # PyMuPDF
PDF_SUPPORT = True
except ImportError:
PDF_SUPPORT = False
print("Warning: PyMuPDF not available, PDF support disabled")
try:
from gtts import gTTS
TTS_SUPPORT = True
except ImportError:
TTS_SUPPORT = False
print("Warning: gTTS not available, audio synthesis disabled")
try:
from groq import Groq
GROQ_SUPPORT = True
except ImportError:
GROQ_SUPPORT = False
print("Warning: Groq not available")
try:
from transformers import pipeline
HF_TRANSFORMERS_SUPPORT = True
except ImportError:
HF_TRANSFORMERS_SUPPORT = False
print("Warning: Transformers not available")
# ✅ Load secrets from environment with better error handling
groq_key = os.environ.get('GROQ_API_KEY')
hf_token = os.environ.get('HF_TOKEN')
kaggle_key = os.environ.get('KAGGLE_KEY')
kaggle_username = os.environ.get('KAGGLE_USERNAME')
# Ensure none of the required secrets are missing
if not all([groq_key, hf_token]):
raise EnvironmentError("❌ One or more required API keys are missing from environment variables.")
# Initialize components with fallbacks
client = None
phishing_pipe = None
if GROQ_SUPPORT and groq_key:
try:
client = Groq(api_key=groq_key)
print("✅ Groq client initialized")
except Exception as e:
print(f"❌ Groq initialization failed: {e}")
if HF_TRANSFORMERS_SUPPORT and hf_token:
try:
phishing_pipe = pipeline(
"text-classification",
model="ealvaradob/bert-finetuned-phishing",
token=hf_token,
return_all_scores=True
)
print("✅ Phishing detection model loaded")
except Exception as e:
print(f"❌ Model loading failed: {e}")
# Try alternative model
try:
phishing_pipe = pipeline(
"text-classification",
model="martin-ha/toxic-comment-model",
return_all_scores=True
)
print("✅ Fallback model loaded")
except Exception as e2:
print(f"❌ Fallback model also failed: {e2}")
# Global variables
history_log = []
detailed_log = []
# 🎯 Role options
role_choices = ["Procurement", "Warehouse", "Admin", "Finance", "Logistics"]
# 🌍 Language options
language_choices = [
"English", "Urdu", "Arabic", "French", "German", "Spanish", "Portuguese", "Hindi", "Turkish",
"Bengali", "Russian", "Chinese", "Japanese", "Korean", "Swahili", "Indonesian", "Italian",
"Dutch", "Polish", "Thai", "Vietnamese", "Romanian", "Persian", "Punjabi", "Greek", "Hebrew",
"Malay", "Czech", "Danish", "Finnish", "Hungarian", "Norwegian", "Slovak", "Swedish", "Tamil",
"Telugu", "Gujarati", "Marathi", "Pashto", "Serbian", "Croatian", "Ukrainian", "Bulgarian",
"Filipino", "Sinhala", "Mongolian", "Kazakh", "Azerbaijani", "Nepali", "Malayalam"
]
# Glossary terms with tooltip
GLOSSARY = {
"phishing": "Phishing is a scam where attackers trick you into revealing personal information.",
"domain spoofing": "Domain spoofing is when someone fakes a legitimate website's address to deceive you.",
"malware": "Malicious software designed to harm or exploit systems.",
"spam": "Unwanted or unsolicited messages.",
"tone": "The emotional character of the message."
}
def extract_text_from_file(file_obj):
"""Extract text from uploaded files with error handling"""
if file_obj is None:
return ""
try:
file_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
ext = file_path.split(".")[-1].lower()
if ext == "pdf" and PDF_SUPPORT:
doc = fitz.open(file_path)
return "\n".join(page.get_text() for page in doc)
elif ext == "txt":
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
else:
return f"Unsupported file type: {ext}"
except Exception as e:
return f"Error reading file: {str(e)}"
def rag_based_reranking(text, bert_analysis, language="English"):
"""
RAG/Prompt-Based Reranking: Use LLaMA to reanalyze and improve BERT's classification
This adds semantic analysis and intent understanding
"""
try:
# Create prompt for LLaMA semantic reanalysis
reranking_prompt = [
{
"role": "system",
"content": f"""
You are an expert cybersecurity analyst specializing in phishing detection.
Your job is to reanalyze email/message content using semantic understanding and intent analysis.
You have received a preliminary classification from a BERT model, but you need to provide a more accurate assessment using your understanding of:
- Social engineering tactics
- Urgency patterns
- Suspicious requests
- Context and intent
- Language patterns that indicate deception
Respond with your reanalysis in this exact format:
REANALYZED_THREAT_TYPE: [safe/spam/phishing/malware]
CONFIDENCE_LEVEL: [low/medium/high]
REASONING: [Brief explanation of your decision]
SEMANTIC_INDICATORS: [What semantic clues led to this conclusion]
"""
},
{
"role": "user",
"content": f"""
ORIGINAL MESSAGE TO ANALYZE:
"{text}"
BERT MODEL'S PRELIMINARY ANALYSIS:
- Classification: {bert_analysis.get('model_prediction', 'Unknown')}
- Threat Type: {bert_analysis.get('threat_type', 'unknown')}
- AI Confidence: {bert_analysis.get('ai_confidence_score', 0)}%
TASK: Does this message pose a phishing, spam, malware, or other security risk?
Use your semantic understanding to reanalyze this message. Consider:
1. Intent and context
2. Social engineering patterns
3. Urgency or pressure tactics
4. Suspicious requests (credentials, money, personal info)
5. Language patterns that suggest deception
6. Overall trustworthiness
Provide your reanalysis using the format specified above.
"""
}
]
# Get LLaMA's semantic reanalysis
response = client.chat.completions.create(
model="llama3-8b-8192",
messages=reranking_prompt,
temperature=0.1, # Low temperature for consistent analysis
max_tokens=500
)
llama_response = response.choices[0].message.content.strip()
# Parse LLaMA's response
reanalysis = parse_llama_reanalysis(llama_response)
# Combine BERT and LLaMA insights
final_analysis = combine_bert_llama_analysis(bert_analysis, reanalysis, text)
return final_analysis
except Exception as e:
print(f"RAG Reranking failed: {e}")
# Fallback to original BERT analysis
bert_analysis['rag_error'] = str(e)
return bert_analysis
def parse_llama_reanalysis(llama_response):
"""Parse LLaMA's structured response"""
reanalysis = {
'llama_threat_type': 'unknown',
'llama_confidence': 'medium',
'llama_reasoning': '',
'semantic_indicators': ''
}
lines = llama_response.split('\n')
for line in lines:
line = line.strip()
if line.startswith('REANALYZED_THREAT_TYPE:'):
reanalysis['llama_threat_type'] = line.split(':', 1)[1].strip().lower()
elif line.startswith('CONFIDENCE_LEVEL:'):
reanalysis['llama_confidence'] = line.split(':', 1)[1].strip().lower()
elif line.startswith('REASONING:'):
reanalysis['llama_reasoning'] = line.split(':', 1)[1].strip()
elif line.startswith('SEMANTIC_INDICATORS:'):
reanalysis['semantic_indicators'] = line.split(':', 1)[1].strip()
return reanalysis
def combine_bert_llama_analysis(bert_analysis, llama_reanalysis, original_text):
"""
Combine BERT and LLaMA analysis using hybrid decision logic
LLaMA's semantic understanding gets priority for final classification
"""
# Get both predictions
bert_threat = bert_analysis.get('threat_type', 'unknown')
llama_threat = llama_reanalysis.get('llama_threat_type', 'unknown')
llama_confidence = llama_reanalysis.get('llama_confidence', 'medium')
# Hybrid decision logic
if llama_confidence == 'high':
# Trust LLaMA's high-confidence assessment
final_threat_type = llama_threat
decision_method = "LLaMA High Confidence"
elif bert_threat == llama_threat:
# Both models agree - high confidence in result
final_threat_type = bert_threat
decision_method = "BERT + LLaMA Agreement"
elif llama_threat == 'safe' and bert_threat in ['spam', 'unknown']:
# LLaMA says safe, BERT unsure - lean towards safe
final_threat_type = 'safe'
decision_method = "LLaMA Safety Override"
elif llama_threat in ['phishing', 'malware'] and bert_threat != 'safe':
# LLaMA detects serious threat - prioritize security
final_threat_type = llama_threat
decision_method = "LLaMA Threat Detection"
else:
# Default to BERT with LLaMA insights
final_threat_type = bert_threat
decision_method = "BERT with LLaMA Insights"
# Create enhanced analysis combining both models
enhanced_analysis = bert_analysis.copy()
enhanced_analysis.update({
'final_threat_type': final_threat_type,
'bert_prediction': bert_threat,
'llama_prediction': llama_threat,
'llama_confidence': llama_confidence,
'llama_reasoning': llama_reanalysis.get('llama_reasoning', ''),
'semantic_indicators': llama_reanalysis.get('semantic_indicators', ''),
'decision_method': decision_method,
'hybrid_analysis': True
})
# Recalculate threat score based on final classification
enhanced_analysis['threat_type'] = final_threat_type
threat_score = calculate_threat_score(enhanced_analysis)
enhanced_analysis['threat_score'] = threat_score
return enhanced_analysis
def calculate_threat_score(hf_analysis):
"""
Calculate threat score based on AI analysis results
Returns score from 0-100 where higher means more dangerous
"""
threat_type = hf_analysis.get('threat_type', 'unknown')
confidence_percentage = hf_analysis.get('ai_confidence_score', 0)
if threat_type == 'safe':
# For safe messages, use INVERSE of confidence
# High confidence in "safe" = Low threat score
threat_score = max(0, min(20, (100 - confidence_percentage) * 0.2))
elif threat_type == 'spam':
# For spam, map confidence to 21-40% range
threat_score = 21 + (confidence_percentage * 0.19)
elif threat_type == 'phishing':
# For phishing, map confidence to 61-80% range
threat_score = 61 + (confidence_percentage * 0.19)
elif threat_type == 'malware':
# For malware, map confidence to 81-100% range
threat_score = 81 + (confidence_percentage * 0.19)
else:
# For unknown threats, use moderate risk
threat_score = 41 + (confidence_percentage * 0.19)
# Ensure score stays within bounds
threat_score = round(min(100, max(0, threat_score)), 1)
# Additional safety check for very short, innocent messages
text = hf_analysis.get('raw_text', '')
if len(text.strip()) <= 10 and threat_type == 'safe':
threat_score = min(threat_score, 10.0)
return threat_score
def analyze_with_huggingface(text):
"""
First stage: Analyze message using Hugging Face BERT model
Returns detailed technical analysis for LLaMA to interpret
FIXED VERSION: Properly handles safe messages like "HI"
"""
try:
# Get prediction from Hugging Face model
result = phishing_pipe(text)
# Extract prediction details
prediction = result[0]
label = prediction['label']
confidence_score = prediction['score']
# Convert to percentage
confidence_percentage = round(confidence_score * 100, 2)
# Map labels to threat types (adjust based on your model's labels)
threat_mapping = {
'PHISHING': 'phishing',
'LEGITIMATE': 'safe',
'SPAM': 'spam',
'MALWARE': 'malware'
}
threat_type = threat_mapping.get(label.upper(), 'unknown')
# FIXED LOGIC: Calculate threat score based on what the model actually detected
if threat_type == 'safe':
# For safe messages, use INVERSE of confidence
# High confidence in "safe" = Low threat score
threat_score = max(0, min(20, (100 - confidence_percentage) * 0.2))
threat_level = "Safe"
elif threat_type == 'spam':
# For spam, map confidence to 21-40% range
threat_score = 21 + (confidence_percentage * 0.19)
threat_level = "Minimal Suspicion"
elif threat_type == 'phishing':
# For phishing, map confidence to 61-80% range
threat_score = 61 + (confidence_percentage * 0.19)
threat_level = "Likely Threat"
elif threat_type == 'malware':
# For malware, map confidence to 81-100% range
threat_score = 81 + (confidence_percentage * 0.19)
threat_level = "Severe Threat"
else:
# For unknown threats, use moderate risk
threat_score = 41 + (confidence_percentage * 0.19)
threat_level = "Needs Attention"
# Ensure score stays within bounds
threat_score = round(min(100, max(0, threat_score)), 1)
# Additional safety check for very short, innocent messages
if len(text.strip()) <= 10 and threat_type == 'safe':
# For very short messages classified as safe, ensure low threat score
threat_score = min(threat_score, 10.0)
threat_level = "Safe"
# Create technical analysis summary for LLaMA
technical_analysis = {
'model_prediction': label,
'ai_confidence_score': confidence_percentage,
'threat_type': threat_type,
'threat_score': threat_score,
'threat_level': threat_level,
'raw_text': text[:500]
}
return technical_analysis
except Exception as e:
# Fallback analysis if Hugging Face model fails
return {
'model_prediction': 'UNKNOWN',
'ai_confidence_score': 0,
'threat_type': 'unknown',
'threat_score': 50.0,
'threat_level': 'Needs Attention',
'raw_text': text[:500],
'error': str(e)
}
def build_enhanced_prompt_messages(hf_analysis, language="English", role="Admin"):
"""
Build prompt that includes both BERT and LLaMA reanalysis for final interpretation
"""
# Check if hybrid analysis was performed
if hf_analysis.get('hybrid_analysis', False):
technical_data = f"""
HYBRID AI ANALYSIS RESULTS:
- BERT Model Prediction: {hf_analysis.get('bert_prediction', 'Unknown')}
- LLaMA Semantic Analysis: {hf_analysis.get('llama_prediction', 'Unknown')}
- Final Classification: {hf_analysis['final_threat_type']}
- Decision Method: {hf_analysis.get('decision_method', 'Standard')}
- LLaMA Confidence: {hf_analysis.get('llama_confidence', 'medium')}
- Threat Score: {hf_analysis['threat_score']}% (0-100, higher = more dangerous)
- LLaMA Reasoning: {hf_analysis.get('llama_reasoning', 'N/A')}
- Semantic Indicators: {hf_analysis.get('semantic_indicators', 'N/A')}
- Original Message: "{hf_analysis['raw_text']}"
"""
else:
technical_data = f"""
STANDARD AI ANALYSIS:
- Model Prediction: {hf_analysis['model_prediction']}
- Detected Threat Type: {hf_analysis['threat_type']}
- Threat Score: {hf_analysis['threat_score']}% (0-100, higher = more dangerous)
- Original Message: "{hf_analysis['raw_text']}"
"""
if 'error' in hf_analysis or 'rag_error' in hf_analysis:
error_msg = hf_analysis.get('error', hf_analysis.get('rag_error', ''))
technical_data += f"\n- Analysis Note: {error_msg}"
return [
{
"role": "system",
"content": f"""
You are a friendly cybersecurity assistant helping employees in the supply chain industry.
You have received results from a hybrid AI analysis system that combines:
1. BERT model for technical pattern detection
2. LLaMA model for semantic understanding and intent analysis
Your job is to explain these results in SIMPLE, NON-TECHNICAL language that anyone can understand.
Guidelines:
- Use everyday words instead of technical jargon
- The threat score ranges from 0-100 where higher numbers mean more dangerous
- Explain both what the computers found AND why it matters
- Give clear, practical advice for a {role} employee
- If there's disagreement between models, explain what that means
Always respond completely in {language} only.
Make it sound like you're talking to a friend, not giving a technical report.
"""
},
{
"role": "user",
"content": f"""
Please analyze this hybrid security check and explain it in simple terms:
{technical_data}
Respond in this format using everyday language:
1. Tone: (How does the message sound? Pushy, friendly, normal, etc.)
2. Threat Type: (What kind of danger is this? Safe message, scam attempt, spam, etc.)
3. Threat Score: (Show the danger level number from 0-100)
4. AI Analysis Summary: (What did both computer systems find? Did they agree?)
5. Simple Explanation (in {language}): (Explain in plain words why this is safe or dangerous)
6. What should you do as a {role} worker (in {language}): (Clear, simple steps)
7. Why the computers flagged this: (Explain what the AI systems noticed)
8. Detailed Advisory (in {language}): (Comprehensive guidance and precautions)
"""
}
]
def get_threat_level_display(threat_score):
"""
Get color-coded threat level display based on corrected 5-level system
"""
if threat_score <= 20:
return "🟢 SAFE - No threat detected"
elif threat_score <= 40:
return "🟡 MINIMAL SUSPICION - Minor concerns"
elif threat_score <= 60:
return "🟠 NEEDS ATTENTION - Requires careful review"
elif threat_score <= 80:
return "🔴 LIKELY THREAT - High probability of danger"
else:
return "⚫ SEVERE THREAT - Immediate action required"
def generate_text_report(analysis_data, hf_analysis, input_text):
"""
Generate a structured text report that can be downloaded as a .txt file
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report = f"""
================================================================================
ZEROPHISH GATE - SECURITY ANALYSIS REPORT
================================================================================
Analysis Date: {timestamp}
Generated by: ZeroPhish Gate AI Security System
================================================================================
ANALYZED MESSAGE
================================================================================
{input_text}
================================================================================
THREAT ASSESSMENT SUMMARY
================================================================================
AI Detection: {hf_analysis.get('model_prediction', 'Unknown')}
Message Type: {hf_analysis.get('threat_type', 'Unknown').title()}
Threat Score: {hf_analysis.get('threat_score', 'N/A')}%
================================================================================
DETAILED ANALYSIS
================================================================================
"""
# Parse detailed analysis sections
sections = {}
current_section = ""
lines = analysis_data.split('\n')
for line in lines:
line = line.strip()
if line.startswith(('1. Tone:', '2. Threat Type:', '3. Threat Score:', '4. Simple Explanation', '5. What should you do', '6. Why the computer', '7. Detailed Advisory')):
current_section = line
sections[current_section] = ""
elif current_section and line and not line.startswith('🤖'):
sections[current_section] += line + " "
# Add detailed analysis sections
section_titles = [
("1. Tone:", "MESSAGE TONE ANALYSIS"),
("2. Threat Type:", "THREAT CLASSIFICATION"),
("3. Threat Score:", "THREAT SCORE ASSESSMENT"),
("4. Simple Explanation", "DETAILED EXPLANATION"),
("5. What should you do", "RECOMMENDED ACTIONS"),
("6. Why the computer", "AI DETECTION REASONING"),
("7. Detailed Advisory", "COMPREHENSIVE ADVISORY")
]
for section_key, section_title in section_titles:
content_text = ""
for key, value in sections.items():
if key.startswith(section_key):
content_text = value.strip()
break
if content_text:
report += f"""
{section_title}
{'-' * len(section_title)}
{content_text}
"""
# Footer
report += f"""
================================================================================
REPORT FOOTER
================================================================================
This report was generated by ZeroPhish Gate AI Security System.
For support or questions, contact your IT security team.
Report ID: ZPG-{timestamp.replace(' ', 'T').replace(':', '-')}
Analysis completed at: {timestamp}
================================================================================
"""
return report
def generate_downloadable_report(analysis_data, hf_analysis, input_text):
"""
Generate a downloadable report file
"""
# Create text report
text_report = generate_text_report(analysis_data, hf_analysis, input_text)
# Create downloadable file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"zerophish_security_report_{timestamp}.txt"
# Create a temporary file for download
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
f.write(text_report)
temp_path = f.name
return temp_path
def add_visual_badges(text):
tags = []
if "urgent" in text.lower():
tags.append("🔴 Urgent Tone Detected")
if "suspicious" in text.lower() and "domain" in text.lower():
tags.append("🗘 Suspicious Domain")
if "safe" in text.lower() or "threat type: safe" in text.lower():
tags.append("🟩 Clean")
if "ai model" in text.lower():
tags.append("🤖 AI-Enhanced Analysis")
if tags:
return text + "\n\n🚨 Visual Tags:\n" + "\n".join(tags)
return text
def apply_glossary_tooltips(text):
"""Apply HTML tooltips for glossary terms"""
# First, convert newlines to HTML breaks
text = text.replace('\n', '
')
# Apply tooltips to glossary terms
for term, definition in GLOSSARY.items():
pattern = re.compile(rf'\b{re.escape(term)}\b', re.IGNORECASE)
# Create HTML span with title attribute for tooltip
tooltip_html = f'{term}'
text = pattern.sub(tooltip_html, text)
# Handle markdown-style bold text
text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
# Wrap in a simple div
html_output = f'
Analyze messages, emails, and documents for potential security threats