import gradio as gr import re import html from transformers import pipeline import numpy as np # Initialize pipelines ocr = pipeline("image-to-text", model="microsoft/trocr-base-printed") # Consider upgrading to trocr-large-printed classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") # Consider fine-tuning for phishing # Common phishing indicators SUSPICIOUS_PHRASES = [ "urgent", "immediately", "password", "account locked", "wire transfer", "bank verification", "click here", "verification code", "credit card", "suspended", "login now", "reset your password", "act now", "unusual activity", "security alert", "confirm your identity", "gift card", "lottery winner" ] # URL detection regex URL_PATTERN = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' def extract_text_from_image(image): if image is None: return "" try: result = ocr(image) return result[0]["generated_text"] if result else "" except Exception as e: return f"Error processing image: {str(e)}" def analyze_text(text): if not text.strip(): return "", "", gr.update(visible=False) # Zero-shot Classification candidate_labels = ["Phishing Email", "Legitimate Email"] result = classifier(text, candidate_labels=candidate_labels) label = result["labels"][0] confidence = result["scores"][0] # Determine risk level and styling if label == "Phishing Email": if confidence > 0.8: alert_html = """
⚠️

High Risk Detected - Likely Phishing Attempt

""" else: alert_html = """

Medium Risk - Suspicious Content Detected

""" else: alert_html = """

Low Risk - Likely Legitimate

""" # Find suspicious phrases and URLs found_phrases = [] text_lower = text.lower() for phrase in SUSPICIOUS_PHRASES: if phrase in text_lower: found_phrases.append(phrase) urls = re.findall(URL_PATTERN, text) # Generate detailed analysis report with modern styling report = [ "
", "

Analysis Details

", f"
", f"
", f"Confidence Score: {confidence:.1%}", "
", f"
", f"Classification: {label}", "
", "
" ] if found_phrases or urls: report.append("
") if found_phrases: report.extend([ "

🚩 Suspicious Elements Detected:

", "") if urls: report.extend([ "

🔗 Detected URLs:

", "") report.append("
") else: report.append("

✅ No common suspicious phrases or URLs detected.

") report.append("
") if confidence > 0.9: report.append("

🔴 High confidence in classification - exercise extreme caution!

") elif confidence > 0.7: report.append("

🟡 Moderate confidence - review carefully and verify sender.

") else: report.append("

🟢 Low confidence - but always remain vigilant.

") report.append("
") return alert_html, "\n".join(report), gr.update(visible=True) def process_input(text_input, image_input): if text_input.strip(): return analyze_text(text_input) if image_input is not None: extracted_text = extract_text_from_image(image_input) if extracted_text.strip(): return analyze_text(extracted_text) return ( """

⚠️ OCR Processing Error

""", "Could not extract text from image. Please ensure the image contains clear, readable text.", gr.update(visible=False) ) return "", "Please provide either text or an image to analyze.", gr.update(visible=False) # Custom theme custom_theme = gr.themes.Soft().set( body_background_fill="#f8f9fa", block_background_fill="white", block_label_background_fill="*background-3", input_background_fill="white", button_primary_background_fill="#1a237e", button_primary_text_color="white", button_secondary_background_fill="#e0e0e0", button_secondary_text_color="#333", ) # CSS for responsiveness and polish custom_css = """ .container { max-width: 1000px; margin: auto; } .header { text-align: center; margin-bottom: 2rem; } .tool-description { max-width: 800px; margin: 0 auto 2rem auto; } .input-section { margin-bottom: 2rem; } .analysis-section { margin-top: 2rem; } @media (max-width: 600px) { .header h1 { font-size: 1.8rem; } .input-section { padding: 0 10px; } .gr-button { width: 100%; margin-bottom: 10px; } } """ # Create Gradio interface with gr.Blocks(theme=custom_theme, css=custom_css) as demo: gr.HTML("""

🛡️ AI Phishing Guard

Protect yourself from phishing attempts with AI-powered analysis

""") with gr.Row(equal_height=True): with gr.Column(): gr.HTML("""

How to Use

  1. Paste message text or upload a screenshot
  2. Analyze instantly as you type or click 'Analyze' for images
  3. Review the detailed results and stay cautious

This tool detects:

""") with gr.Tabs(): with gr.TabItem("✏️ Text Input"): text_input = gr.Textbox( lines=8, label="Message Text", placeholder="Paste email or message content here...", elem_id="text_input" ) with gr.TabItem("📷 Screenshot Upload"): image_input = gr.Image( label="Upload Screenshot", type="pil", elem_id="image_input" ) with gr.Row(): analyze_button = gr.Button("🔍 Analyze", variant="primary", size="lg") clear_button = gr.Button("🗑️ Clear", variant="secondary", size="lg") loading = gr.HTML("
Analyzing...
", visible=False) with gr.Column(visible=False) as output_col: alert_html = gr.HTML() analysis = gr.HTML() # Examples examples = [ ["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 at https://fakebank.com/reset. If you don't respond within 24 hours, your account will be suspended.\n\nBank Security Team", None], ["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], ] gr.Examples( examples=examples, inputs=[text_input, image_input], outputs=[alert_html, analysis, output_col], fn=process_input, cache_examples=True ) # Event handlers def with_loading(*args): return (gr.update(visible=True), *process_input(*args), gr.update(visible=False)) text_input.change( fn=process_input, inputs=[text_input, image_input], outputs=[alert_html, analysis, output_col] ) analyze_button.click( fn=with_loading, inputs=[text_input, image_input], outputs=[loading, alert_html, analysis, output_col] ) clear_button.click( fn=lambda: ("", None, "", "", gr.update(visible=False)), inputs=[], outputs=[text_input, image_input, alert_html, analysis, output_col] ) # Launch the app if __name__ == "__main__": demo.launch()