import gradio as gr from analyze_email_main import analyze from weasyprint import HTML import tempfile def html_to_pdf(html_content): """Convert HTML string to a temporary PDF file and return its path.""" with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf: HTML(string=html_content).write_pdf(tmp_pdf.name) return tmp_pdf.name def analyze_email(file_path): if file_path is None: return "

Please upload a .eml file to analyze.

", None # Get structured results summary, details = analyze(file_path) # Safely extract summary fields attack_score = summary.get("Attack Score", 0) try: score_val = int(round(float(attack_score))) except Exception: score_val = 0 score_val = max(0, min(score_val, 100)) attack_type = summary.get("Attack Type", "Unknown") verdict = summary.get("Final Verdict", "No Verdict") # Verdict color verdict_color = "#2ecc71" v_lower = verdict.lower() if "malicious" in v_lower: verdict_color = "#e74c3c" elif "suspicious" in v_lower: verdict_color = "#e67e22" elif "spam" in v_lower: verdict_color = "#f1c40f" # Collect details safely header_findings = details.get("Header Findings", []) or [] body_findings = details.get("Body Findings", []) or [] url_findings = details.get("URL Findings", []) or [] highlighted_body = details.get("Highlighted Body", "") or "" auth_results = details.get("Auth Results", None) # Render authentication results safely if isinstance(auth_results, dict): auth_html = "" elif isinstance(auth_results, str): auth_html = f"

{auth_results}

" else: auth_html = "

No auth results found.

" # Tags main_tags_str = summary.get("Main Tags", "") tags = [t.strip() for t in main_tags_str.split(",")] if main_tags_str else [] # HTML Report html = f"""

📧 Email Security Report

Attack Score

{score_val}/100

Attack Type: {attack_type}

Final Verdict: {verdict}

🔖 Attack Analysis Tags ({len(tags)}) {"" if tags else "

No special tags

"}
🛡 Authentication Results {auth_html}
🕵️ Detailed Findings

Headers ({len(header_findings)})

{"" if header_findings else "

No header findings.

"}

Body ({len(body_findings)})

{"" if body_findings else "

No body findings.

"}

URLs ({len(url_findings)})

{"" if url_findings else "

No URL findings.

"}
📩 Highlighted Email Body
{highlighted_body}
""" # ALWAYS generate PDF try: pdf_path = html_to_pdf(html) except Exception as e: pdf_path = None html += f"

PDF export failed: {e}

" return html, pdf_path # Gradio Interface (checkbox removed) demo = gr.Interface( fn=analyze_email, inputs=[ gr.File(label="Upload .eml File", type="filepath") ], outputs=[ gr.HTML(label="Analysis Report"), gr.File(label="Download PDF Report") ], title="📧 Email Security Analyzer", description="Upload an .eml file to detect phishing, spam, or malicious emails. A PDF report will be generated automatically." ) demo.launch()