Anupam251272 commited on
Commit
00a1906
1 Parent(s): a552fdc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ import numpy as np
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
+
6
+ class ThreatAnalyzer:
7
+ def __init__(self):
8
+ # Load pretrained model for threat detection
9
+ model_name = 'distilbert-base-uncased-finetuned-sst-2-english'
10
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
11
+ self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
12
+
13
+ def analyze_threat(self, input_text):
14
+ """
15
+ Comprehensive threat analysis with recommendations
16
+ """
17
+ # Detect threat probability
18
+ inputs = self.tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
19
+ outputs = self.model(**inputs)
20
+ predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
21
+ threat_score = predictions[0][1].item()
22
+
23
+ # Categorize threat types
24
+ threat_patterns = {
25
+ "phishing": ["verify", "urgent", "suspend", "account", "click here"],
26
+ "social_engineering": ["tech support", "password", "credentials", "urgent"],
27
+ "malware": ["download", "patch", "update", "critical"],
28
+ "impersonation": ["admin", "support", "verify identity"]
29
+ }
30
+
31
+ # Analyze input for specific threat patterns
32
+ detected_patterns = []
33
+ for threat_type, keywords in threat_patterns.items():
34
+ if any(keyword.lower() in input_text.lower() for keyword in keywords):
35
+ detected_patterns.append(threat_type)
36
+
37
+ # Generate recommendations based on threat analysis
38
+ recommendations = []
39
+ if threat_score > 0.7:
40
+ recommendations.extend([
41
+ "🚨 High Risk: Do NOT interact with this message",
42
+ "Immediately report to IT security",
43
+ "Do not click any links or download attachments"
44
+ ])
45
+ elif threat_score > 0.4:
46
+ recommendations.extend([
47
+ "⚠️ Potential Threat Detected",
48
+ "Verify the source independently",
49
+ "Contact sender through official channels"
50
+ ])
51
+
52
+ # If specific threat patterns detected, add specific advice
53
+ if "phishing" in detected_patterns:
54
+ recommendations.append("Phishing Indicator: Check sender's email address carefully")
55
+ if "social_engineering" in detected_patterns:
56
+ recommendations.append("Social Engineering Alert: Never share personal credentials")
57
+ if "malware" in detected_patterns:
58
+ recommendations.append("Malware Risk: Scan with updated antivirus before opening")
59
+
60
+ return {
61
+ "threat_score": threat_score,
62
+ "threat_level": self._classify_threat_level(threat_score),
63
+ "detected_patterns": detected_patterns,
64
+ "recommendations": recommendations
65
+ }
66
+
67
+ def _classify_threat_level(self, score):
68
+ """Classify threat level"""
69
+ if score > 0.8: return "CRITICAL THREAT"
70
+ if score > 0.6: return "HIGH THREAT"
71
+ if score > 0.4: return "MODERATE THREAT"
72
+ if score > 0.2: return "LOW THREAT"
73
+ return "NO SIGNIFICANT THREAT"
74
+
75
+ def launch_threat_analysis_demo():
76
+ """Create Gradio interface for threat analysis"""
77
+ analyzer = ThreatAnalyzer()
78
+
79
+ def analyze_input(input_text):
80
+ try:
81
+ result = analyzer.analyze_threat(input_text)
82
+
83
+ # Format output for clear presentation
84
+ output = f"""
85
+ 🔍 Threat Analysis Results:
86
+
87
+ Threat Score: {result['threat_score']:.2%}
88
+ Threat Level: {result['threat_level']}
89
+
90
+ Detected Threat Patterns:
91
+ {', '.join(result['detected_patterns']) or 'No specific patterns identified'}
92
+
93
+ Recommendations:
94
+ {chr(10).join('• ' + rec for rec in result['recommendations'])}
95
+
96
+ 💡 Always verify suspicious communications
97
+ """
98
+ return output
99
+ except Exception as e:
100
+ return f"Error in analysis: {str(e)}"
101
+
102
+ # Gradio interface
103
+ with gr.Blocks() as demo:
104
+ gr.Markdown("# Cybersecurity Threat Analysis")
105
+
106
+ input_text = gr.Textbox(label="Enter suspicious text or message")
107
+ output_text = gr.Textbox(label="Threat Analysis Results")
108
+
109
+ analyze_btn = gr.Button("Analyze Threat")
110
+ analyze_btn.click(fn=analyze_input, inputs=input_text, outputs=output_text)
111
+
112
+ return demo
113
+
114
+ # Run the demo
115
+ if __name__ == "__main__":
116
+ demo = launch_threat_analysis_demo()
117
+ demo.launch(debug=True, share=True)