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 = "{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"""Attack Type: {attack_type}
Final Verdict: {verdict}
No special tags
"}No header findings.
"}No body findings.
"}No URL findings.
"}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()